<?php

namespace controller\admin;

defined('IA_ROOT') || exit();

use facade\View;
use facade\Model;
use facade\Util;

// 控制器
class Index extends Base
{
    // 后台首页
    public function index()
    {
        $menus = array_filter($this->auth, function ($item) {
            return in_array($item['id'], $this->user['role']['auth_ids']) && $item['status'] == 0 && $item['is_menu'] == 0;
        });
        // 无限层级递归
        $menus = Util::levels($menus);
        // 无限级菜单
        $menus = $this->menus($menus);
        $avatar = '';
        if (preg_match('#(/static/upload/[^\.]+\.(gif|jpe?g|png|bmp|webp|psd|svg|tiff))#i', $this->user['avatar'], $match)) {
            $avatar = $this->site_url . $match[1];
        }
        View::assign([
            'menus' => $menus,
            'username' => $this->user['username'],
            'avatar' => $avatar,
            'version' => 'v1.0.0'
        ]);
        View::display('admin/index.html');
    }

    // 欢迎页面
    public function welcome()
    {
        $userCount = Model::fetchColumn("SELECT COUNT(*) FROM `user` ORDER BY `id`");
        $articleCount = Model::fetchColumn("SELECT COUNT(*) FROM `article` ORDER BY `id`");
        $commentCount = Model::fetchColumn("SELECT COUNT(*) FROM `comment` ORDER BY `id`");
        $check = Model::fetch("SELECT VERSION()");
        $data = Model::fetchAll("SELECT * FROM `comment` WHERE `pid` = 0 ORDER BY `sort` DESC, `id` DESC LIMIT 5");
        $authors = [];
        $aids = [];
        foreach ($data as $item) {
            $authors[] = $item['author'];
            $aids[] = $item['article_id'];
        }
        $authors = array_unique($authors);
        $authors = implode("','", $authors);
        $users = Model::fetchAll("SELECT * FROM `user` WHERE `username` IN ('$authors')");
        $aids = array_unique($aids);
        $aids = implode(',', $aids);
        if ($aids) {
            $articles = Model::fetchAll("SELECT * FROM `article` WHERE `status` = 0 AND `id` IN ($aids) ORDER BY `id`");
        } else {
            $articles = [];
        }
        $data = array_map(function ($item) use ($users, $articles) {
            // 评论图像
            $item['avatar'] = '';
            if ($user = array_filter($users, function ($elem) use ($item) {
                return $elem['username'] == $item['author'];
            })) {
                $user = array_values($user);
                $item['nickname'] = $user[0]['nickname'] ?: $user[0]['username'];
                $item['avatar'] = $user[0]['avatar'] ? $this->site_url . '/' . ltrim($user[0]['avatar'], '/') : '';
            }
            // 被评论的文章
            $item['article_title'] = $item['author'];
            $item['article_link'] = '#';
            if ($article = array_filter($articles, function ($elem) use ($item) {
                return $elem['id'] == $item['article_id'];
            })) {
                $article = array_values($article);
                $item['article_title'] = $article[0]['title'];
                $item['article_link'] = $this->site_url . "/{$this->replace_path}" . ($article[0]['slug'] ? $article[0]['slug'] : $article[0]['id']) . '.html';
            }
            return $item;
        }, $data);
        $commentList = $data;
        // 统计图表
        $week = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
        $data = Model::fetchAll("SELECT DATE_FORMAT(FROM_UNIXTIME(`reg_time`), '%Y-%m-%d') AS date, COUNT(*) AS count FROM `user` WHERE `reg_time` >= UNIX_TIMESTAMP(DATE_SUB(CURDATE(), INTERVAL 7 DAY)) GROUP BY date ORDER BY `reg_time` ASC");
        $users = array_map(function ($item) {
            $item['w'] = date("w", strtotime($item['date']));
            return $item;
        }, $data);
        $data = Model::fetchAll("SELECT DATE_FORMAT(FROM_UNIXTIME(`create_at`), '%Y-%m-%d') AS date, COUNT(*) AS count FROM `article` WHERE `create_at` >= UNIX_TIMESTAMP(DATE_SUB(CURDATE(), INTERVAL 7 DAY)) GROUP BY date ORDER BY `create_at` ASC");
        $articles = array_map(function ($item) {
            $item['w'] = date("w", strtotime($item['date']));
            return $item;
        }, $data);
        $data = Model::fetchAll("SELECT DATE_FORMAT(FROM_UNIXTIME(`time`), '%Y-%m-%d') AS date, COUNT(*) AS count FROM `comment` WHERE `time` >= UNIX_TIMESTAMP(DATE_SUB(CURDATE(), INTERVAL 7 DAY)) GROUP BY date ORDER BY `time` ASC");
        $comments = array_map(function ($item) {
            $item['w'] = date("w", strtotime($item['date']));
            return $item;
        }, $data);
        $datas = array_reduce($users, function ($prev, $next) use ($week) {
            $prev[$next['w']] = ['user_count' => $next['count'], 'user_date' => $next['date'], 'user_week' => $week[$next['w']]];
            return $prev;
        }, []);
        $datas = array_reduce($articles, function ($prev, $next) use ($week) {
            $prev[$next['w']] = array_merge(isset($prev[$next['w']]) ? $prev[$next['w']] : [], ['article_count' => $next['count'], 'article_date' => $next['date'], 'article_week' => $week[$next['w']]]);
            return $prev;
        }, $datas);
        $datas = array_reduce($comments, function ($prev, $next) use ($week) {
            $prev[$next['w']] = array_merge(isset($prev[$next['w']]) ? $prev[$next['w']] : [], ['comment_count' => $next['count'], 'comment_date' => $next['date'], 'comment_week' => $week[$next['w']]]);
            return $prev;
        }, $datas);
        $charts = ['weeks' => [], 'users' => [], 'articles' => [], 'comments' => []];
        foreach ($datas as $key => $value) {
            $charts['weeks'][] = $week[$key];
            $charts['users'][] = isset($value['user_count']) ? $value['user_count'] : 0;
            $charts['articles'][] = isset($value['article_count']) ? $value['article_count'] : 0;
            $charts['comments'][] = isset($value['comment_count']) ? $value['comment_count'] : 0;
        }
        View::assign([
            'userCount' => $userCount,
            'articleCount' => $articleCount,
            'commentCount' => $commentCount,
            'databaseInfo' => array_shift($check),
            'serverCurrentTime' => date('Y-m-d H:i:s'),
            'commentList' => $commentList,
            'charts' => json_encode($charts),
        ]);
        View::display('admin/index/welcome.html');
    }

    // 无限级菜单
    private function menus($dataArr)
    {
        $res = '';
        foreach ($dataArr as $k => $data) {
            $res .= $this->childMenus($data, $k);
        }
        return $res;
    }

    // 递归子数据
    private function childMenus($data, $k = 0, $indent = 0)
    {
        $res = '';
        if ($data['children']) {
            $res .= sprintf('<li class="layui-nav-item%s">', $k === 0 ? ' layui-nav-itemed' : '');
            $res .= sprintf('<a href="javascript:;" style="text-indent:%dem;" title="%s">%s%s</a>', max($indent, 0), strip_tags($data['title']), $data['icon'] ? '<i class="' . $data['icon'] . '"></i> ' : '', $data['title']);
            $res .= '<dl class="layui-nav-child">';
            foreach ($data['children'] as $k => $data) {
                if ($data['children']) {
                    $res .= $this->childMenus($data, $k, $indent + 1);
                } else {
                    $res .= sprintf('<dd><a href="javascript:;" style="text-indent:%dem;" data-module="%s" data-controller="%s" data-action="%s" lay-header-event="fireMenu" title="%s">%s%s</a></dd>', $indent + 1, $this->module, $data['controller'], $data['action'], strip_tags($data['title']), $data['icon'] ? '<i class="' . $data['icon'] . '"></i> ' : '', $data['title']);
                }
            }
            $res .= '</dl>';
            $res .= "</li>\n";
        } else {
            $res .= sprintf('<li class="layui-nav-item%s"><a href="javascript:;" data-module="%s" data-controller="%s" data-action="%s" lay-header-event="fireMenu" title="%s">%s%s</a></li>', $k === 0 ? ' layui-this' : '', $this->module, $data['controller'], $data['action'], strip_tags($data['title']), $data['icon'] ? '<i class="' . $data['icon'] . '"></i> ' : '', $data['title']);
        }
        return $res;
    }
}
